package com.taobao.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class JDBCConnecter_local {
	private final static String DRIVER = "com.mysql.jdbc.Driver"; 
	private String URL;
	private String USER;
	private String PWD;
	
	private Connection con = null;
	private Statement stmt = null;
	
	public JDBCConnecter_local(String url, String user, String pwd) {
		this.URL = url;
		this.USER = user;
		this.PWD = pwd;
	}
	
	/**
	 * Connect to database
	 * @return
	 */
	public boolean connectDB(){
		try{
			Class.forName(DRIVER);
			con = DriverManager.getConnection(this.URL, this.USER, this.PWD);
			stmt = con.createStatement();
		}
		catch(ClassNotFoundException e1){
			System.out.println("Database driver is not exist!");
			System.out.println(e1.toString());
			return false;
		}
		catch(SQLException e2){
			System.out.println("Database throws exception!");
			System.out.println(e2.toString());
			return false;
		}
		
		return true;
	}
	
	public ResultSet executeQuery(String cmd){
		ResultSet rs = null;
		
		try {
			rs = this.stmt.executeQuery(cmd);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		
		return rs;
	}
	
	public int executeInsert(String cmd){
		
		try {
			return this.stmt.executeUpdate(cmd);
		} catch (SQLException e) {
			e.printStackTrace();
			return -1;
		}
	}
	
	public void closeDB(){
		try{
			if(stmt != null) stmt.close();
			if(con != null) con.close();
		}
		catch(SQLException e){
			System.out.println(e.toString());
		}    
	}
	
}
